package co.wizardattack.model;

import co.wizardattack.connection.MessageDistpacher;
import co.wizardattack.constants.ResourcesNames;

import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import java.io.IOException;
import org.andengine.audio.music.Music;
import org.andengine.audio.music.MusicFactory;
import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.font.FontManager;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import protocol.OnNewMessageListener;
import protocol.PairedConnection;
import protocol.Print;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.util.Log;

public class Game implements IOnSceneTouchListener, OnNewMessageListener {

	// Constantes
	private static int CAMERA_WIDTH = 1080;
	private static int CAMERA_HEIGHT = 720;
	// Atributos
	private Context context;
	private Wizard theWizard;
	private Scene sceneGame;
	private Camera cameraGame;
	private VertexBufferObjectManager vertexBffObjManager;
	private Media media;
	/**
	 * Atributos de prueba
	 */
	private BitmapTextureAtlas atlasFondo;
	private BitmapTextureAtlas atlasAnimacion;
	private ITextureRegion texturaFondo;
	private Sprite spriteFondo;
	private ITiledTextureRegion texturaAnimada;
	private AnimatedSprite spriteAnimado;
	private Sprite spriteAccesorio;
	private ITextureRegion texturaAccesorio;
	private float rotacionAccesorio = 1;	
	private Font miFuente;
	private Text miTexto;
	private int cuenta = 0;	

	private float factorDeMovimiento = 50;
	/**
	 * Fin de Atributos de prueba
	 */

	// Conexion
	private PairedConnection pairedConnection;



















	public Game(Context context) {
		this.context = context;
		MessageDistpacher.INSTANCE.setListener(this);
	}

	public Camera createCamera() {
		cameraGame = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		return cameraGame;
	}








	@Override
	public int onNewMessage(String message) {
		// Receiving a message from the other player
		Print.print("wizardgame",message);
		try{ cuenta = Integer.valueOf(message); } catch(Exception e) {}
		miTexto.setText("Score: " + cuenta);
		return message.length();
	}

	@Override
	public void getPairedConnection(PairedConnection connection) {
		// Saving the PairedConnection to comunicate
		this.pairedConnection = connection;
	}

	@Override
	public void onCloseConnection() {
		// Do something with BattleActivity
	}











	public void onCreateResources(TextureManager textureManager, FontManager fontManager, AssetManager assetManager, Engine engine) throws IOException {

		// Loading music and sound effects
		this.media = new Media(context, engine.getSoundManager(), engine.getMusicManager());
		// Cargando recursos		
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(ResourcesNames.IMAGES_PATH);		
		//Cargando fondo
		atlasFondo = new BitmapTextureAtlas(textureManager, 1080, 720,TextureOptions.DEFAULT);
		texturaFondo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasFondo, context, "escenario.png", 0, 0);		




		//Cargando Wizard
		atlasAnimacion = new BitmapTextureAtlas(textureManager, 1080, 720,TextureOptions.DEFAULT);
		texturaAnimada = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(atlasAnimacion, context, "secuencia.png", 75, 0, 3, 4);

		//carcando AccesorioWizard ==> getAtlasAnimatedWizard()
		texturaAccesorio = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasAnimacion, context, "accpluma.png", 0, 0);


		//fondo
		atlasFondo.load();
		//wizard

		atlasAnimacion.load();
		FontFactory.setAssetBasePath(ResourcesNames.FUENTES_PATH);

		final ITexture fontTexture = new BitmapTextureAtlas(textureManager, 256, 256, TextureOptions.BILINEAR);
		miFuente = FontFactory.createFromAsset(fontManager, fontTexture, assetManager, ResourcesNames.FUENTE_NOMBRE, 100, true, Color.WHITE);
		miFuente.load();	
	}









	public Scene onCreateScene(VertexBufferObjectManager vertexBufferObjectManager) {

		// Saving the vertx
		this.vertexBffObjManager = vertexBufferObjectManager;

		// Starting music
		this.media.playMusic();

		// Starting the scenary
		sceneGame = new Scene();
		sceneGame.setOnSceneTouchListener(this);	
		spriteFondo = new Sprite(1080/2, 720/2, texturaFondo, vertexBufferObjectManager);
		spriteAnimado = new AnimatedSprite(300, 275, texturaAnimada, vertexBufferObjectManager);
		spriteAccesorio = new Sprite(spriteAnimado.getWidth()*0.1f, spriteAnimado.getHeight()*1.25f, texturaAccesorio, vertexBufferObjectManager){ 
			@Override
			protected void onManagedUpdate(float pSecondsElapsed) {		 
				spriteAccesorio.setRotation(spriteAccesorio.getRotation() + rotacionAccesorio);
				if(spriteAccesorio.getRotation() > 10.5f)
					rotacionAccesorio*=-1;		 
				if(spriteAccesorio.getRotation() < -10.5f)
					rotacionAccesorio*=-1;		 
				super.onManagedUpdate(pSecondsElapsed);
			}
		};
		spriteAnimado.attachChild(spriteAccesorio);
		long[] duracionFrame = { 200, 200, 200, 200, 200, 200};
		spriteAnimado.animate(duracionFrame, 0, 5, true);
		sceneGame.attachChild(spriteFondo);		
		sceneGame.attachChild(spriteAnimado);
		///TEXTO///////////////////////////////////
		miTexto = new Text(cameraGame.getWidth()*0.2f, cameraGame.getHeight()*0.8f, miFuente, "Score:0123456789", vertexBufferObjectManager);
		miTexto.setText("Score: " + cuenta);
		sceneGame.attachChild(miTexto);		
		return sceneGame;
	}







	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		long[] duracionFrame = { 200, 200, 200 };
		if(pSceneTouchEvent.isActionDown()){
			media.playEffect(media.EFFECT_FIRE);
			cuenta++;
			//			String error = pairedConnection == null ? "SS" : "";
			miTexto.setText("Score: " + cuenta);
			if(pairedConnection != null)
				pairedConnection.sendMessage(""+cuenta);
			if(spriteAnimado.getX() > cameraGame.getWidth()){
				factorDeMovimiento*=-1;
				spriteAnimado.animate(duracionFrame, 9, 11, true);
			}
			if(spriteAnimado.getX()< 0){
				factorDeMovimiento*=-1;
				spriteAnimado.animate(duracionFrame, 3, 5, true);
			}
			spriteAnimado.setX(spriteAnimado.getX()+ factorDeMovimiento);
		}
		return false;
	}






}
